# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.shortcuts import redirect
from basic import models
from django.db.models import Q,QuerySet
from django.core.paginator import Paginator
from basic.models import instance_info
import ast
from django.http import JsonResponse, HttpResponse
# Create your views here.
from django.forms.models import model_to_dict
import json
import cx_Oracle
import time


##分页函数,传入三个参数：
# queryset结果集、当前页、每页显示的条目数
#分页方法
def v_paginator(data, current_page_num, line_count_set):
    # 以下是分页
    # 5条一页
    # 总页数：paginator.num_pages
    # 当前页：current_page_num
    # 当前页数据：current_page
    # 总行数：paginator.count
    # 页数列表 paginator_num_pages_list
    global paginator
    global current_page
    global page_range
    global paginator_num_pages_list
    # paginator = Paginator(data, 5)  # 对所有数据进行分页
    paginator = Paginator(data, line_count_set)
    global last_page
    last_page = paginator.num_pages

    paginator_num_pages_list = [ x for x in range(1,paginator.num_pages+1)]
    # if paginator_num_pages_list==[]:
    #     paginator_num_pages_list = [1]
    try:  # 捕捉前台传过来的数据，传过来不正常的数据都跳到第一页
        global current_page
        current_page = paginator.page(current_page_num)  # 拿哪一页
        if paginator.num_pages > 11:  # 判断总页数是否大于 10 页
            if current_page_num - 5 < 1:  # 页数小于前5页就显示前10页
                current_range = range(1, 11)
                page_range = current_range
                return current_range, current_page, paginator, page_range, last_page, paginator_num_pages_list
            elif current_page_num + 5 > paginator.num_pages:  # 页数大于最后5页就显示最后10页
                current_range = range(paginator.num_pages - 10, paginator.num_pages + 1)
                page_range = current_range
                return current_range, current_page, paginator, page_range, last_page, paginator_num_pages_list
            else:
                current_range = range(current_page_num - 4, current_page_num + 4)  # 其他范围为-5页到+5页
                page_range = current_range
                return current_range, current_page, paginator, page_range, last_page, paginator_num_pages_list
        else:
            page_range = paginator.page_range  # 小于10页就显示所有页数
            return page_range, current_page, paginator, page_range, last_page, paginator_num_pages_list

    except Exception as e:
        current_page_num = 1  # 随便乱传取第一页
        current_page = paginator.page(current_page_num)  # 随便乱传则取第一页
        current_range = range(1, 12)
        return paginator, current_page, current_range, page_range, last_page, paginator_num_pages_list




###用户登入
def login(request):
    error_msg = ""
    if request.method == 'POST':
        user = request.POST.get('user',None)
        pwd = request.POST.get('pwd',None)
        #request.session['username'] = user
        login_obj = models.user_info.objects.filter(username=user,password=pwd).first()
        if login_obj:
            request.session['username'] = user
            request.session['is_login'] = True
            if login_obj.status == 'LOCKED':
                error_msg = "该用户状态为'LOCKED'"
                return render(request, 'basic_app/login.html', {'error_msg': error_msg})
            # return redirect('/basic_app/user')
            return redirect('/oratk_app/oratk_query')
            # return render(request,'/basic_app/user.html',{'userinfo':user})
            #return HttpResponse("登入成功")
        else:
            error_msg = "用户名或密码错误"
            #print request.path
            return render(request, 'basic_app/login.html', {'error_msg': error_msg})
    if request.method == 'GET':
        return render(request, 'basic_app/login.html', {'error_msg':error_msg})

##用户登出
def logout(request):
    if request.method == 'GET':
        ##请空session
        request.session.clear()
        return redirect('/basic_app/login.html')
"""def user_add(request):
    ##创建数据
    models.user_info.objects.create(username='test',password='test')
    ##查询 result 是对象列表 queryset类型
    ##查询所有
    #result = models.user_info.objects.all()
    ##带条件查询
    result = models.user_info.objects.filter(username='root')
    for row in result:
        print(row.username,row.password)
    ##删除
    #models.user_info.objects.filter(username='root').delete()
    ##更新
    models.user_info.objects.all().update(password='123')
"""


##用户展示页
# def user(request):
#     if request.method == 'POST':
#         pass
#     if request.method == 'GET':
#         if request.session.get('is_login',None):
#             ##关闭浏览器删除session
#             request.session.set_expiry(0)
#             userinfo_result = models.user_info.objects.all()
#             return render(request, 'basic_app/user.html', {'userinfo_result':userinfo_result})
#         else:
#             return redirect('/basic_app/login.html')
##加分页
# def user(request):
#     if request.method == 'POST':
#         pass
#     if request.method == 'GET':
#         if request.session.get('is_login',None):
#             ##关闭浏览器删除session
#             request.session.set_expiry(0)
#             userinfo_result = models.user_info.objects.all()
#
# #以下是分页
#             #5条一页
#             #总页数：paginator.num_pages
#             #当前页：current_page_num
#             #当前页数据：current_page
#             #总行数：paginator.count
#             paginator = Paginator(userinfo_result, 5)  # 对所有数据进行分页
#             try:  # 捕捉前台传过来的数据，传过来不正常的数据都跳到第一页
#                 current_page_num = int(request.GET.get('page'))  # 前台传过来的要拿一页
#                 current_page = paginator.page(current_page_num)  # 拿哪一页
#                 #print(current_page.object_list)  # 拿哪一页的所有数据
#
#                 # 这可以循环当前页的对象 paginator.page 也可以循环当前页的内容 current_page.object_list
#                 # for item in current_page:
#                 #     print(item.name)
#
#                 if paginator.num_pages > 11:  # 判断总页数是否大于 10 页
#                     if current_page_num - 5 < 1:  # 页数小于前5页就显示前10页
#                         current_range = range(1, 11)
#                     elif current_page_num + 5 > paginator.num_pages:  # 页数大于最后5页就显示最后10页
#                         current_range = range(paginator.num_pages - 10, paginator.num_pages + 1)
#                     else:
#                         current_range = range(current_page_num - 5, current_page_num + 5)  # 其他范围为-5页到+5页
#                 else:
#                     page_range = paginator.page_range  # 小于10页就显示所有页数
#
#             except Exception as e:
#                 current_page_num = 1  # 随便乱传取第一页
#                 current_page = paginator.page(current_page_num)  # 随便乱传则取第一页
#                 current_range = range(1, 12)
# #以上是分页
#             return render(request, 'basic_app/user.html', locals())
#             # return render(request, 'basic_app/user.html', {'userinfo_result':userinfo_result})
#         else:
#             return redirect('/basic_app/login.html')
# def user(request):
#     if request.method == 'POST':
#         pass
#     if request.method == 'GET':
#         if request.session.get('is_login',None):
#             ##关闭浏览器删除session
#             request.session.set_expiry(0)
#             userinfo_result = models.user_info.objects.all()
#             #v_paginator 为分页函数
#             #参数为：
#                 # userinfo_result： queryset 结果集
#                 # currentpage_num:当前选着的页数,默认为1
#                 # line_count_set：每页显示的条目数,默认为5
#             currentpage_num = int(request.GET.get('page','1'))
#             line_count_set = int(request.GET.get('line_count',5))
#             v_paginator(userinfo_result,currentpage_num,line_count_set)
#             return render(request, 'basic_app/user.html', {'current_page':current_page,'paginator':paginator,'line_count':line_count_set,'page_range':page_range,'current_page_num':currentpage_num})
#             # return render(request, 'basic_app/user.html',locals())
#
#         else:
#             return redirect('/basic_app/login.html')


###dashboard
def dashboard(request):
    if request.method == 'POST':
        pass
    if request.session.get('is_login', None):
        ##关闭浏览器删除session
        request.session.set_expiry(0)
        ins_active_info = []
        ins_inactive_info = []
        ins_locked_info = []
        ins_total_info = []
        ins_oracle_locked = models.instance_info.objects.filter(status='LOCKED', type='ORACLE').count()
        ins_mysql_locked = models.instance_info.objects.filter(status='LOCKED', type='MYSQL').count()
        ins_other_locked = models.instance_info.objects.filter(status='LOCKED').exclude(type='MYSQL').exclude(
            type='ORACLE').count()

        ins_oracle_failed = models.instance_info.objects.filter(ins_active='FAILED', type='ORACLE').count()
        ins_mysql_failed = models.instance_info.objects.filter(ins_active='FAILED', type='MYSQL').count()
        ins_other_failed = models.instance_info.objects.filter(ins_active='FAILED').exclude(type='MYSQL').exclude(
            type='ORACLE').count()

        ins_oracle_success = models.instance_info.objects.filter(ins_active='SUCCESS', type='ORACLE').count()
        ins_mysql_success = models.instance_info.objects.filter(ins_active='SUCCESS', type='MYSQL').count()
        ins_other_success = models.instance_info.objects.filter(ins_active='SUCCESS').exclude(
            type='MYSQL').exclude(type='ORACLE').count()

        ins_total_oracle = models.instance_info.objects.filter(type='ORACLE').count()
        ins_total_mysql = models.instance_info.objects.filter(type='MYSQL').count()
        ins_total_other = models.instance_info.objects.filter().exclude(type='MYSQL').exclude(
            type='ORACLE').count()

        ins_active_info.append(ins_oracle_success)
        ins_active_info.append(ins_mysql_success)
        ins_active_info.append(ins_other_success)
        ins_inactive_info.append(ins_oracle_failed)
        ins_inactive_info.append(ins_mysql_failed)
        ins_inactive_info.append(ins_other_failed)
        ins_locked_info.append(ins_oracle_locked)
        ins_locked_info.append(ins_mysql_locked)
        ins_locked_info.append(ins_other_locked)
        ins_total_info.append(ins_total_oracle)
        ins_total_info.append(ins_total_mysql)
        ins_total_info.append(ins_total_other)
        return render(request, 'basic_app/dashboard.html',
                      {'ins_active_info': ins_active_info, 'ins_inactive_info': ins_inactive_info,
                       'ins_locked_info': ins_locked_info, 'ins_total_info': ins_total_info})
    else:
        return redirect('/basic_app/login.html')




#####uesr展示页+搜索
def user(request):
    if request.method == 'POST':
        pass
    if request.method == 'GET':
        if request.session.get('is_login',None):
            ##关闭浏览器删除session
            request.session.set_expiry(0)

            #v_paginator 为分页函数
            #参数为：
            # userinfo_result： queryset 结果集
            # currentpage_num:当前选着的页数,默认为1
            # line_count_set：每页显示的条目数,默认为5
            currentpage_num = int(request.GET.get('page','1'))
            line_count_set = int(request.GET.get('line_count',5))
            user_search = request.GET.get('user_search','all')
            ##当用户搜索时：
            if user_search != 'all':
                userinfo_result = models.user_info.objects.filter(Q(email__contains=user_search)
                                                                  | Q(username__contains=user_search)
                                                                  | Q(iphone__contains=user_search)
                                                                  | Q(status__contains=user_search))
                v_paginator(userinfo_result, currentpage_num, line_count_set)
            #当用户没有搜索时：
            else:
                user_search = ''
                userinfo_result = models.user_info.objects.all()
                v_paginator(userinfo_result,currentpage_num,line_count_set)

            return render(request, 'basic_app/user.html', {'current_page':current_page,'paginator':paginator,'line_count':line_count_set,
                                                           'page_range':page_range,'last_page':last_page,'current_page_num':currentpage_num,'paginator_num_pages_list':paginator_num_pages_list
                ,'search':user_search})
            # return render(request, 'basic_app/user.html',locals())

        else:
            return redirect('/basic_app/login.html')
##用户—添加
def user_add_edit(request):
    if request.method == 'POST':
        edit_id = request.POST.get('add_id', '')
        add_user = request.POST.get('add_user', None)
        add_pwd = request.POST.get('add_pwd', None)
        add_email = request.POST.get('add_email', None)
        add_phone = request.POST.get('add_phone', None)
        add_dept = request.POST.get('add_dept', None)
        add_status = request.POST.get('add_status', None)
        if len(edit_id) >0:
            models.user_info.objects.filter(id=edit_id).update(username=add_user, password=add_pwd, email=add_email,
                                                            iphone=add_phone
                                                            , status=add_status, dept=add_dept)
        else:
            models.user_info.objects.create(username=add_user, password=add_pwd,email=add_email,iphone=add_phone
                                            ,dept=add_dept,status=add_status)
        return redirect("/basic_app/user")

    if request.method == 'GET':
        if request.session.get('is_login',None):
            ##关闭浏览器删除session
            request.session.set_expiry(0)
            nid = request.GET.get('nid')
            edit_result = models.user_info.objects.filter(id=nid)
            userinfo_result = {}
            for val in edit_result:
                val = model_to_dict(val)
                userinfo_result = dict(userinfo_result, **(val))
            return HttpResponse(json.dumps(userinfo_result), content_type='application/json')
        else:
            return redirect('/basic_app/login.html')
###用户搜索废弃，已整合到用户展示页
##用户-搜索
# def user_search(request):
#     if request.method == 'POST':
#         user_search = request.POST.get('user_search', None)
#         ##多条件模糊 查询
#         # type__name__contains
#         if user_search:
#             user_search_result = models.user_info.objects.filter(Q(email__contains=user_search)
#                                                                  |Q(username__contains=user_search)
#                                                                  |Q(iphone__contains=user_search)
#                                                                  |Q(status__contains=user_search))
#             currentpage_num = int(request.GET.get('page','1'))
#             line_count_set = int(request.GET.get('line_count',5))
#             v_paginator(user_search_result,currentpage_num,line_count_set)
#             return render(request, 'basic_app/user.html', {'current_page':current_page,'paginator':paginator,'line_count':line_count_set,'page_range':page_range,'current_page_num':currentpage_num})
#             # return render(request, 'basic_app/user.html', {'userinfo_result': user_search_result})
#         else:
#             return redirect("/basic_app/user")
#     if request.method == 'GET':
#         if request.session.get('is_login',None):
#             ##关闭浏览器删除session
#             request.session.set_expiry(0)
#             return redirect("/basic_app/user")
#         else:
#             return redirect('/basic_app/login.html')

##用户编辑
# def user_edit(request):
#     if request.method == 'POST':
#         v_id = request.POST.get('v_id', None)
#         add_user = request.POST.get('add_user', None)
#         add_pwd = request.POST.get('add_pwd', None)
#         add_email = request.POST.get('add_email', None)
#         add_phone = request.POST.get('add_phone', None)
#         add_dept = request.POST.get('add_dept', None)
#         add_status = request.POST.get('add_status', None)
#         models.user_info.objects.filter(id=v_id).update(username=add_user, password=add_pwd, email=add_email, iphone=add_phone
#                                                         ,status=add_status, dept=add_dept)
#         return redirect("/basic_app/user")
#     if request.method == 'GET':
#         if request.session.get('is_login',None):
#             ##关闭浏览器删除session
#             request.session.set_expiry(0)
#             nid = request.GET.get('nid')
#             edit_result = models.user_info.objects.get(id=nid)
#             return render(request, 'basic_app/user_edit.html',{'userinfo_result': edit_result})
#         else:
#             return redirect('/basic_app/login.html')

##用户删除
def user_delete(request):
    if request.method == 'POST':
        pass
    if request.method == 'GET':
        if request.session.get('is_login',None):
            ##关闭浏览器删除session
            request.session.set_expiry(0)
            nid = request.GET.get('nid')
            models.user_info.objects.filter(id=nid).delete()
            return redirect("/basic_app/user")
        else:
            return redirect('/basic_app/login.html')

##用户锁定
def user_lock(request):
    if request.method == 'POST':
        pass
    if request.method == 'GET':
        if request.session.get('is_login',None):
            ##关闭浏览器删除session
            request.session.set_expiry(0)
            nid = request.GET.get('nid')
            models.user_info.objects.filter(id=nid).update(status='LOCKED')
            return redirect("/basic_app/user")
        else:
            return redirect('/basic_app/login.html')

##用户信息详情
def user_more(request):
    if request.method == 'POST':
        return redirect("/basic_app/user")
    if request.method == 'GET':
        if request.session.get('is_login',None):
            ##关闭浏览器删除session
            request.session.set_expiry(0)
            nid = request.GET.get('nid')
            more_result = models.user_info.objects.get(id=nid)
            return render(request, 'basic_app/user_more.html', {'more_result': more_result})
        else:
            return redirect('/basic_app/login.html')



##实例展示页
# def instance(request):
#     if request.method == 'POST':
#         pass
#     if request.method == 'GET':
#         if request.session.get('is_login',None):
#             ##关闭浏览器删除session
#             request.session.set_expiry(0)
#             instanceinfo_result = models.instance_info.objects.all()  # type: QuerySet[instance_info]
#             return render(request, 'basic_app/instance.html', {'instanceinfo_result':instanceinfo_result})
#         else:
#             return redirect('/basic_app/login.html')
def instance(request):
    if request.method == 'POST':
        pass
    if request.method == 'GET':
        if request.session.get('is_login',None):
            ##关闭浏览器删除session
            request.session.set_expiry(0)
            #v_paginator 为分页函数
            #参数为：
            # userinfo_result： queryset 结果集
            # currentpage_num:当前选着的页数,默认为1
            # line_count_set：每页显示的条目数,默认为5
            currentpage_num = int(request.GET.get('page','1'))
            line_count_set = int(request.GET.get('line_count',5))
            user_search = request.GET.get('user_search','all')
            ##当用户搜索时：
            if user_search != 'all':
                instanceinfo_result = models.instance_info.objects.filter(Q(dbname__contains=user_search)
                                                                          | Q(ip__contains=user_search)
                                                                          | Q(port__contains=user_search)
                                                                          | Q(conn_string__contains=user_search)
                                                                          | Q(sid__contains=user_search)
                                                                          | Q(status__contains=user_search)
                                                                          | Q(type__contains=user_search)
                                                                          | Q(remark__contains=user_search)
                                                                          | Q(ins_active__contains=user_search)
                                                                          ).order_by('dbname')
                v_paginator(instanceinfo_result, currentpage_num, line_count_set)
            #当用户没有搜索时：
            else:
                user_search = ''
                instanceinfo_result = models.instance_info.objects.all().order_by('dbname')
                v_paginator(instanceinfo_result,currentpage_num,line_count_set)
            return render(request, 'basic_app/instance.html', {'current_page':current_page,'paginator':paginator,'line_count':line_count_set,
                                                               'page_range':page_range,'last_page':last_page,'current_page_num':currentpage_num,'paginator_num_pages_list':paginator_num_pages_list
                ,'search':user_search})
        else:
            return redirect('/basic_app/login.html')

##实例添加或编辑
def instance_add_edit(request):
    if request.method == 'POST':
        try:
            ##搜索和分页信息
            line_count_set =  request.POST.get('line_count_set', None)
            page_set = request.POST.get('page_set', None)
            search = request.POST.get('search', None)
            ##要新增或更改的信息
            edit_id = request.POST.get('add_id', '')
            add_dbname = request.POST.get('add_dbname', None)
            add_ip = request.POST.get('add_ip', None)
            add_port = request.POST.get('add_port', None)
            add_sid = request.POST.get('add_sid', None)
            add_conn_string = request.POST.get('add_conn_string', None)
            add_remark = request.POST.get('add_remark', None)
            add_type = request.POST.get('add_type', None)
            add_status = request.POST.get('add_status', None)
            add_service_name = request.POST.get('add_service_name',None)
            if len(edit_id) > 0:
                path = '/basic_app/instance' + '?page=%s&line_count=%s&user_search=%s'%(page_set,line_count_set,search)
                models.instance_info.objects.filter(id=edit_id).update(dbname=add_dbname, ip=add_ip, port=add_port,
                                                    sid=add_sid, conn_string=add_conn_string,service_name=add_service_name,
                                                    remark=add_remark, type=add_type,status=add_status)
                return HttpResponse(path)
            else:
                models.instance_info.objects.create(dbname=add_dbname, ip=add_ip, port=add_port,
                                                    sid=add_sid, conn_string=add_conn_string,service_name=add_service_name,
                                                    remark=add_remark, type=add_type,status=add_status)
                return HttpResponse("/basic_app/instance")
        except Exception as err:
            return HttpResponse("AJAX_ERR:  %s "% (err))

    if request.method == 'GET':
        if request.session.get('is_login',None):
            ##关闭浏览器删除session
            request.session.set_expiry(0)
            nid = request.GET.get('nid')

            edit_result = models.instance_info.objects.filter(id=nid)
            instanceinfo_result = {}
            for val in edit_result:
                val = model_to_dict(val)
                instanceinfo_result = dict(instanceinfo_result, **(val))
            return HttpResponse(json.dumps(instanceinfo_result), content_type='application/json')
        else:
            return redirect('/basic_app/login.html')


##实例——删除
def instance_delete(request):
    if request.method == 'POST':
        pass
    if request.method == 'GET':
        if request.session.get('is_login',None):
            ##关闭浏览器删除session
            request.session.set_expiry(0)
            nid = request.GET.get('nid')
            models.instance_info.objects.filter(id=nid).delete()
            return redirect("/basic_app/instance")
        else:
            return redirect('/basic_app/login.html')

##实例——锁定
def instance_lock(request):
    if request.method == 'POST':
        pass
    if request.method == 'GET':
        if request.session.get('is_login',None):
            ##关闭浏览器删除session
            request.session.set_expiry(0)
            nid = request.GET.get('nid')
            models.instance_info.objects.filter(id=nid).update(status='LOCKED')
            return redirect("/basic_app/instance")
        else:
            return redirect('/basic_app/login.html')

##实例信息详情
def instance_more(request):
    if request.method == 'POST':
        return redirect("/basic_app/instance")
    if request.method == 'GET':
        if request.session.get('is_login',None):
            ##关闭浏览器删除session
            request.session.set_expiry(0)
            nid = request.GET.get('nid')
            more_result = models.instance_info.objects.get(id=nid)
            return render(request, 'basic_app/instance_more.html', {'more_result': more_result})
        else:
            return redirect('/basic_app/login.html')



##实例探活
def instance_ins_check(request):
    curr_time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    if request.method == 'POST':
        return redirect("/basic_app/instance")
    if request.method == 'GET':
        if request.session.get('is_login',None):
            ##关闭浏览器删除session
            request.session.set_expiry(0)
            nid = request.GET.get('nid',None)
            line_count_set = request.GET.get('line_count_set', None)
            page_set = request.GET.get('page_set', None)
            search = request.GET.get('search', None)
            active_check_sql = '''
                                select 1 from dual
                                '''
            if not nid:
                #如果nid为none #一次探活
                #获取全部实例，循环
                ins_info = models.instance_info.objects.values('id','conn_string').all()
                success_count = 0
                failed_count = 0
                total_count = 0
                for ins in ins_info:
                    total_count = total_count +1
                    try:
                        db = cx_Oracle.connect('dbmonitor', 'ghsdbmon1tor', ins['conn_string'])
                        conn_cursor = db.cursor()
                        conn_cursor.execute(active_check_sql)
                        ##获取结果
                        result = conn_cursor.fetchall()
                        ins_active = 'SUCCESS'
                        ins_active_msg = 'SUCCESS'
                        success_count =success_count +1
                    except Exception as err:
                        ins_active = 'FAILED'
                        ins_active_msg = err
                        failed_count = failed_count +1
                    models.instance_info.objects.filter(id=ins['id']).update(ins_active=ins_active,
                                                                           ins_active_msg=ins_active_msg,
                                                                             ins_active_time=curr_time_str)
                json_info = {'ins_check_type':'all', 'total_c':total_count,'success_c':success_count,'failed_c':failed_count,'url':'/basic_app/instance'}
                return JsonResponse(json_info)
            else:
                #如果nid不为none
               #单次探活
                ins_info = models.instance_info.objects.values('id', 'conn_string').get(id=nid)
                try:
                    db = cx_Oracle.connect('dbmonitor', 'ghsdbmon1tor', ins_info['conn_string'])
                    conn_cursor = db.cursor()
                    conn_cursor.execute(active_check_sql)
                    ##获取结果
                    result = conn_cursor.fetchall()
                    ins_active = 'SUCCESS'
                    ins_active_msg = 'SUCCESS'
                except Exception as err:
                    ins_active = 'FAILED'
                    ins_active_msg = err
                models.instance_info.objects.filter(id=nid).update(ins_active=ins_active,ins_active_msg=ins_active_msg,ins_active_time=curr_time_str)
                path = '/basic_app/instance' + '?page=%s&line_count=%s&user_search=%s'%(page_set,line_count_set,search)
                json_info = {'ins_check_type':'one','url':path}
                return JsonResponse(json_info)
        else:
            return redirect('/basic_app/login.html')
##主机展示
def host(request):
    if request.method == 'POST':
        pass
    if request.method == 'GET':
        if request.session.get('is_login',None):
            request.session.set_expiry(0)
            currentpage_num = int(request.GET.get('page','1'))
            line_count_set = int(request.GET.get('line_count',5))
            user_search = request.GET.get('user_search','all')
            if user_search != 'all':
                hostinfo_result = models.host_info.objects.filter(Q(name__contains=user_search)
                                                                  | Q(hostname__contains=user_search)
                                                                  | Q(ip__contains=user_search)
                                                                  | Q(gm_ip__contains=user_search)
                                                                  | Q(other_ip__contains=user_search)
                                                                  | Q(status__contains=user_search)
                                                                  | Q(type__contains=user_search)
                                                                  | Q(remark__contains=user_search)
                                                                  | Q(place__contains=user_search)
                                                                  )
                v_paginator(hostinfo_result, currentpage_num, line_count_set)
            else:
                user_search = ''
                hostinfo_result = models.host_info.objects.all()
                v_paginator(hostinfo_result,currentpage_num,line_count_set)
            return render(request, 'basic_app/host.html', {'current_page':current_page,'paginator':paginator,'line_count':line_count_set,
                                                           'page_range':page_range,'current_page_num':currentpage_num,'paginator_num_pages_list':paginator_num_pages_list
                ,'search':user_search})
        else:
            return redirect('/basic_app/login.html')


##主机添加、修改
def host_add_edit(request):
    if request.method == 'POST':
        try:
            ##搜索和分页信息
            line_count_set = request.POST.get('line_count_set', None)
            page_set = request.POST.get('page_set', None)
            search = request.POST.get('search', None)
            ##要新增或更改的信息
            edit_id = request.POST.get('add_id', '')
            add_name = request.POST.get('add_name', None)
            add_hostname = request.POST.get('add_hostname', None)
            add_desc = request.POST.get('add_desc',None)
            add_ip = request.POST.get('add_ip', None)
            add_port = request.POST.get('add_port', None)
            add_gm_ip = request.POST.get('add_gm_ip', None)
            add_other_ip = request.POST.get('add_other_ip', None)
            add_status = request.POST.get('add_status', None)
            add_type = request.POST.get('add_type', None)
            add_osversion = request.POST.get('add_osversion', None)
            add_remark = request.POST.get('add_remark', None)
            add_place = request.POST.get('add_place', None)

            #判断编辑还是新增
            if len(edit_id)  >0 :
                path = '/basic_app/host' + '?page=%s&line_count=%s&user_search=%s'%(page_set,line_count_set,search)
                models.host_info.objects.filter(id=edit_id).update(name=add_name, hostname=add_hostname, desc=add_desc, ip=add_ip,
                                                port=add_port, gm_ip=add_gm_ip,
                                                other_ip=add_other_ip, status=add_status, type=add_type,
                                                osversion=add_osversion,
                                                remark=add_remark, place=add_place)
                return HttpResponse(path)

            else:
                models.host_info.objects.create(name=add_name,hostname=add_hostname,desc=add_desc,ip=add_ip,port=add_port,gm_ip=add_gm_ip,
                                            other_ip=add_other_ip,status=add_status,type=add_type,osversion=add_osversion,
                                            remark=add_remark,place=add_place)
                return HttpResponse("/basic_app/host")
        except Exception as err:
            return HttpResponse("AJAX_ERR:  %s " % (err))


    if request.method == 'GET':
        if request.session.get('is_login',None):
            request.session.set_expiry(0)
            nid = request.GET.get('nid')
            edit_result = models.host_info.objects.filter(id=nid)
            hostinfo_result = {}
            for val in edit_result:
                val = model_to_dict(val)
                hostinfo_result = dict(hostinfo_result, **(val))
            return HttpResponse(json.dumps(hostinfo_result), content_type='application/json')
        else:
            return redirect('/basic_app/login.html')


def host_delete(request):
    if request.method == 'POST':
        pass
    if request.method == 'GET':
        if request.session.get('is_login',None):
            request.session.set_expiry(0)
            nid = request.GET.get('nid')
            models.host_info.objects.filter(id=nid).delete()
            return redirect("/basic_app/host")
        else:
            return redirect('/basic_app/login.html')

##主机锁定
def host_lock(request):
    if request.method == 'POST':
        pass
    if request.method == 'GET':
        if request.session.get('is_login',None):
            ##???????session
            request.session.set_expiry(0)
            nid = request.GET.get('nid')
            models.host_info.objects.filter(id=nid).update(status='停用')
            return redirect("/basic_app/host")
        else:
            return redirect('/basic_app/login.html')

##主机详情
def host_more(request):
    if request.method == 'POST':
        return redirect("/basic_app/host")
    if request.method == 'GET':
        if request.session.get('is_login',None):
            ##???????session
            request.session.set_expiry(0)
            nid = request.GET.get('nid')
            more_result = models.host_info.objects.get(id=nid)
            return render(request, 'basic_app/host_more.html', {'more_result': more_result})
        else:
            return redirect('/basic_app/login.html')






##APP-展示页
def app(request):
    if request.method == 'POST':
        pass
    if request.method == 'GET':
        if request.session.get('is_login',None):
            ##关闭浏览器删除session
            request.session.set_expiry(0)
            appinfo_result = models.user_info.objects.all()
            return render(request, 'basic_app/app.html', {'appinfo_result':appinfo_result})
        else:
            return redirect('/basic_app/login.html')
